import {
	type AnyRoute,
	type AnyRouter,
	DefaultGlobalNotFound,
	invariant,
	matchContext,
	useRouter,
	useRouterState,
	warning,
} from "@tanstack/react-router";
import React from "react";

export const useOutlet = () => {
	const router = useRouter();
	const matchId = React.useContext(matchContext);

	const routeId = useRouterState({
		select: (s) => s.matches.find((d) => d.id === matchId)?.routeId as string,
	});

	const route = router.routesById[routeId]! as AnyRoute;

	const parentGlobalNotFound = useRouterState({
		select: (s) => {
			const matches = s.matches;
			const parentMatch = matches.find((d) => d.id === matchId);
			invariant(
				parentMatch,
				`Could not find parent match for matchId "${matchId}"`,
			);
			return parentMatch.globalNotFound;
		},
	});

	const childMatchId = useRouterState({
		select: (s) => {
			const matches = s.matches;
			const index = matches.findIndex((d) => d.id === matchId);
			return matches[index + 1]?.id;
		},
	});

	if (parentGlobalNotFound) {
		return renderRouteNotFound(router, route, undefined);
	}

	if (!childMatchId) {
		return null;
	}

	// const nextMatch = <Match matchId={childMatchId} />;

	// const pendingElement = router.options.defaultPendingComponent ? <router.options.defaultPendingComponent /> : null;

	// if (matchId === rootRouteId) {
	// 	return <React.Suspense fallback={pendingElement}>{nextMatch}</React.Suspense>;
	// }

	// return nextMatch;

	const childRoute = router.routesById[childMatchId] as AnyRoute;
	const Comp = childRoute.options.component ?? router.options.defaultComponent;
	if (Comp) {
		return (
			<>
				<Comp />
				{/* {routeId === rootRouteId && router.options.scrollRestoration && (
					<>
						<OnRendered />
					</>
				)} */}
			</>
		);
	}
	return null;
};

function renderRouteNotFound(
	router: AnyRouter,
	route: AnyRoute,
	// biome-ignore lint/suspicious/noExplicitAny: <explanation>
	data: any,
) {
	if (!route.options.notFoundComponent) {
		if (router.options.defaultNotFoundComponent) {
			return <router.options.defaultNotFoundComponent data={data} />;
		}

		if (process.env.NODE_ENV === "development") {
			warning(
				route.options.notFoundComponent,
				`A notFoundError was encountered on the route with ID "${route.id}", but a notFoundComponent option was not configured, nor was a router level defaultNotFoundComponent configured. Consider configuring at least one of these to avoid TanStack Router's overly generic defaultNotFoundComponent (<div>Not Found<div>)`,
			);
		}

		return <DefaultGlobalNotFound />;
	}

	return <route.options.notFoundComponent data={data} />;
}
